<?php

namespace Cck\ArticlesSystem\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ArticleResource extends JsonResource
{
    public function toArray($request)
    {
        if (is_null($this->resource)) {
            return [];
        }

        $this->resource->append('url');

        $result = $this->resource->toArray();

        $result['category'] = $this->whenLoaded('category', function () {
            return new CategoryResource($this->resource->category);
        });

        $result['tags'] = $this->whenLoaded('tags', function () {
            return TagResource::collection($this->resource->tags);
        });

        return $result;
    }
}
